package com.eve.controller.admin;

import com.eve.entity.BlogCategory;
import com.eve.service.BlogCategoryService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;
import java.util.List;

@Controller
@RequestMapping("/admin")
public class BlogCategoryController {
    @Autowired
    private BlogCategoryService blogCategoryService;

    //分页查询分类列表

    @GetMapping("/showcategory")
    public String list(Model model,@RequestParam(defaultValue = "1",value = "pageNum") Integer pageNum){
        PageHelper.startPage(pageNum,7);

        List<BlogCategory> list =blogCategoryService.getAllCategory();

//        System.out.println("++++++"+list);
        PageInfo<BlogCategory> pageInfo = new PageInfo<BlogCategory>(list);

        model.addAttribute("pageInfo",pageInfo);
//        System.out.println("-------pangeInfo----"+pageInfo);
        return "admin/category";
    }

    //添加功能
    @GetMapping("/addcategory")
    public String addcategory(@Valid BlogCategory blogCategory,RedirectAttributes attributes){
        BlogCategory blogCategory1 = blogCategoryService.getCategoryByName(blogCategory.getCategory_name());
//        System.out.println(blogCategory1);
        if (blogCategory1 != null) {
            attributes.addFlashAttribute("message", "不能添加重复的分类");
            return "redirect:/admin/showcategory";
        }
        int t = blogCategoryService.saveCategory(blogCategory);
        if (t == 0) {
            attributes.addFlashAttribute("message", "新增失败");
        } else {
            attributes.addFlashAttribute("message", "新增成功");
        }
        return "redirect:/admin/showcategory";
    }

    //删除
    @GetMapping("/categorydelete")
    public String deleteStudent(Integer id){
        blogCategoryService.deleteCategory(id);
        return "redirect:/admin/showcategory";
    }
}
